<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧树形菜单优化 -->
      <el-col :span="5">
        <div class="tree-container">
          <el-card shadow="hover">
            <el-scrollbar style="height: calc(100vh - 250px)">
              <el-tree
                :data="deptOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                node-key="treeId"
                default-expand-all
                highlight-current
                @node-click="handleNodeClick"
              />
            </el-scrollbar>
          </el-card>
        </div>
      </el-col>

      <!-- 右侧内容区优化 -->
      <el-col :span="19">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          class="search-form"
          label-width="100px"
        >
          <el-form-item label="项目组成员">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入项目组成员姓名"
              clearable
              size="small"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >新增</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          height="400"
          :data="templateList"
          :row-style="{ height: '30px' }"
          border
          :cell-style="{ padding: '0px' }"
        >
          <el-table-column
            label="序号"
            type="index"
            align="center"
            prop="index"
            :index="indexMethod"
          />
          <el-table-column
            label="产品类别"
            align="center"
            width="120"
            prop="typeId"
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.product_type"
                :value="scope.row.typeId"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="项目组成员"
            align="center"
            :show-overflow-tooltip="true"
            prop="userName"
          />
          <el-table-column
            label="联系方式"
            align="center"
            prop="contact"
            width="120"
          />
          <el-table-column
            label="职位"
            align="center"
            prop="position"
            width="120"
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="60"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                 title="删除"
              />
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 用户选择组件 -->
    <select-user
      ref="select"
      :type="userType"
      :sign="sign"
      :selectedData="selectedUserData"
      @ok="selectUser"
    />
  </div>
</template>

<script>
import {
  qualificationTree,
  listTemplate,
  delTemplate,
  batchAddTemplate,
} from "@/api/member/template";
import SelectUser from "@/views/system/role/selectUserInfo.vue";

export default {
  name: "Template",
  dicts: ["product_type"],
  components: {
    SelectUser,
  },
  data() {
    return {
      // 选择用户相关
      userType: "0", // 0表示多选
      sign: "1", // 1表示从用户列表选择
      selectedUserData: [], // 已选用户数据，用于回显

      // 树形配置
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },

      // 表格相关
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      templateList: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        userName: null,
        typeId: null,
      },
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 获取部门树 */
    getDeptTree() {
      qualificationTree().then(response => {
        this.deptOptions = response.data;
      });
    },

    /** 树节点过滤 */
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    /** 节点点击事件 */
    handleNodeClick(data) {
      if (data.treeId === "0") {
        this.queryParams.typeId = null;
      } else {
        this.queryParams.typeId = data.treeId;
      }
      // 刷新列表
      this.handleQuery();
    },

    /** 获取列表数据 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        // 更新已选用户数据
        this.selectedUserData = response.rows.map(item => ({
          userId: item.userId,
          nickName: item.userName,
          phonenumber: item.contact,
          position: item.position,
        }));
        this.loading = false;
      });
    },

    /** 序号计算方法 */
    indexMethod(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.queryParams.userName = null;
      this.queryParams.typeId = null;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      if (!this.queryParams.typeId) {
        this.$modal.msgError("请先选择左侧产品类别");
        return;
      }
      this.$refs.select.show();
    },

    /** 选择用户回调 */
    selectUser(userIds, nickNames, phones, positions) {
      if (Array.isArray(userIds)) {
        this.loading = true;
        // 构建成员列表数据
        const memberList = userIds.map((userId, index) => ({
          typeId: this.queryParams.typeId,
          userId: userId,
          userName: nickNames[index],
          contact: phones[index],
          position: positions[index],
        }));

        // 调用批量新增方法
        batchAddTemplate(this.queryParams.typeId, memberList)
          .then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("保存成功");
              this.getList();
            } else {
              this.$modal.msgError("保存失败：" + response.msg);
            }
          })
          .catch(error => {
            this.$modal.msgError("保存失败：" + (error.message || "未知错误"));
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除项目组成员为"' + row.userName + '"的数据项？')
        .then(function () {
          return delTemplate(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>

<style scoped>
.tree-container {
  margin-bottom: 20px;
}
::v-deep {
  .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background-color: #1890ff;
    color: white;
  }
}
</style>
